import Schema, { Values } from "async-validator";
import { Rules } from "async-validator/dist-types/interface";
import { Context } from "koa";

async function validate<T extends Values>(ctx: Context, rules: Rules): Promise<{data: T, error: any | null}>{
    const validator = new Schema(rules);
    let data: any = {};

    switch(ctx.method){
        case "GET":
            break;
        case "POST":
        case "PUT":
            data = getFormData(ctx);
            break;
        case "DELETE":
            break;
    }
    return await validator.validate(data).then(() => {
        return {
            data: data as T,
            error: null
        };
    }).catch(err => {
        return {
            data: {} as T,
            error: err.errors[0]
        };
    })
}


function getFormData(ctx: Context){
    return ctx.request.body || {};
}


export default validate;